import yaml

from common.logging_use import Logger
from config import YAML_LOG


class YamlUtils:

    logger = Logger.init_log_config(__name__, YAML_LOG)

    @staticmethod
    def _handle_error(e, operation, path=None):
        if isinstance(e, FileNotFoundError):
            YamlUtils.logger.error(f"在{operation}过程中，File not found: {path}")
            return None
        if isinstance(e, yaml.YAMLError):
            YamlUtils.logger.error(f"在{operation}过程中，Error parsing YAML file: {e}")
            return None
        if isinstance(e, KeyError):
            YamlUtils.logger.error(f"在{operation}过程中,输入无效的key")
            return None
        else:
            YamlUtils.logger.error(f"在{operation}过程中,An unexpected error occurred: {e}")
            return None

    @staticmethod
    def read_data(path, key=None, user=''):
        try:
            with open(path, 'r', encoding='utf-8') as f:
                data = yaml.load(stream=f, Loader=yaml.FullLoader)
                if key:
                    YamlUtils.logger.info(f"路径：{path}，数据读取成功,\n  执行者为：{user}")
                    return data[key]
                else:
                    YamlUtils.logger.info(f"路径：{path}，数据读取成功,\n  执行者为：{user}")
                    return data
        except Exception as e:
            YamlUtils._handle_error(e, "reading", path)
            return None

    @staticmethod
    def write_data_with_w(path, data, user=''):
        try:
            with open(path, 'w', encoding='utf-8') as f:
                yaml.dump(data, stream=f, allow_unicode=True)
            YamlUtils.logger.info(f"路径：{path}，方式“w”,\n   数据写入成功,执行者为：{user}")
        except Exception as e:
            YamlUtils._handle_error(e, "write_data_with_w", path)

    @staticmethod
    def write_data_with_a(path, data, user=''):
        try:
            with open(path, 'a', encoding='utf-8') as f:
                yaml.dump(data, stream=f, allow_unicode=True)
            YamlUtils.logger.info(f"路径：{path}，方式“a”，\n   数据写入成功,执行者为：{user}")
        except Exception as e:
            YamlUtils._handle_error(e, "write_data_with_a", path)
            return None

    @staticmethod
    def clear_data(path, user=None):
        try:
            with open(path, 'w', encoding='utf-8') as f:
                f.write('')
                YamlUtils.logger.info(f"路径：{path}，数据清除成功,\n  执行者为：{user}")
        except Exception as e:
            YamlUtils._handle_error(e, "clear_data", path)


if __name__ == '__main__':
    yaml_utils = YamlUtils()
    data = {}
    caseinfo = yaml_utils.read_data('../data/login.yaml',user='lmm')
    caseinfo = caseinfo[0]
    data["username"] = caseinfo["body"]["username"]
    data["password"] = caseinfo["body"]["password"]
    data["code"] = caseinfo["body"]["code"]
    print(data)
